<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Models\Admin\AdminUser;
use Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
	/*
	|--------------------------------------------------------------------------
	| Login Controller
	|--------------------------------------------------------------------------
	|
	| This controller handles authenticating users for the application and
	| redirecting them to your home screen. The controller uses a trait
	| to conveniently provide its functionality to your applications.
	|
     */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/admin';
    protected $username;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'logout']);
    }

    /**
     * 重写登录视图页面
     */
    public function showLoginForm()
    {
        return view('admin.auth.login');
    }

    /**
     * 自定义认证驱动
     */
    protected function guard()
    {
        return auth()->guard('admin');
    }


    /**
     * @author ACEYNG
     * 通过数据库检测用户登陆
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse  */
    public function checkLogin(Request $request)
    {

        $email = $request->email;
        $password = $request->password;
        if (auth()->guard('admin')->attempt(['email' => $email, 'password' => $password, 'status' => 1])) {
            AdminUser::where('id', $this->guard()->user()->id)->update(['last_login' => time()]);
            return response()->json(codeArray('success', '1', '登录成功'));
        } else {
            return response()->json(codeArray('fail', '2', '请检查账号密码'));
        }
    }

    /**
     * 退出 Log the user out of the application.
     * 重定向
     */
    public function logout()
    {

        $this->guard('admin')->logout();
        return redirect('/admin/login');
    }

    public function register()
    {
        return view('admin.auth.register');
    }

    public function forgotpassword()
    {
        return view('admin.auth.password');
    }
}
